const express = require('express')
const router = express.Router()
const userController = require('./controllers/user.js')
const sessionController = require('./controllers/session.js')
const topicController = require('./controllers/topic.js')

function checkLogin (req, res, next) {
	const {user} = req.session
	if ( ! user) {
		return res.status(401).json({
			error : 'Unauthorized'
		})
	}
	next()
}

/**
 * 用户资源
 */
router
	.get('/users', userController.list)
	.post('/users', userController.create)
	.patch('/users/:id', userController.update)
	.delete('/users/:id', userController.destroy)

router
	.get('/topics', topicController.list)
	.post('/topics', checkLogin, topicController.create)
	.patch('/topics/:id', checkLogin, topicController.modify)
	.delete('/topics/:id', checkLogin, topicController.destroy)

/**
 * 会话管理
 */
router
	.get('/session', sessionController.get)
	.post('/session', sessionController.create)
	.delete('/session', sessionController.destroy)

module.exports = router